package cn.edu.scut.sys.controller;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.edu.scut.sys.service.UserService;
import cn.edu.scut.sys.utils.DataRequest;
import cn.edu.scut.sys.utils.DataResponse;
import cn.edu.scut.sys.utils.StringUtils;
import cn.edu.scut.sys.vo.User;


@Controller
@RequestMapping("/user")
public class UserController {

	private UserService userService;

	@Resource(name="userService")
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	/**
	 * 
	 * @param page
	 * @param rows
	 * @param sidx
	 * @param sord
	 * @param search
	 * @param searchField
	 * @param searchOper
	 * @param searchString
	 * @param filters
	 * @return
	 */
	@RequestMapping("/list")
	@ResponseBody
	public DataResponse<User> list(@RequestParam(defaultValue="1",value="page") String page,  
            @RequestParam(defaultValue="20",value="rows") String rows,  
            @RequestParam("sidx") String sidx,  
            @RequestParam("sord") String sord,  
            @RequestParam("search") boolean search,  
            @RequestParam(required=false,value="searchField") String searchField,  
            @RequestParam(required=false,value="searchOper") String searchOper,  
            @RequestParam(required=false,value="searchString") String searchString,  
            @RequestParam(required=false,value="filters") String filters  
            ){  
		 try {  
	            DataRequest request = new DataRequest();  
	            request.setPage(StringUtils.isEmpty(page) ? 1 : Integer.valueOf(page));  
	            request.setRows(StringUtils.isEmpty(rows) ? 20 : Integer.valueOf(rows));  
	            request.setSidx(sidx);  
	            request.setSord(sord);  
	            request.setSearch(search);  
	            request.setSearchField(searchField);  
	            request.setSearchOper(searchOper);  
	            request.setSearchString(searchString);  
	            return userService.list(request);  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	        return null;  
	}
	
	@RequestMapping("/add")
	public String add(String name, String password,String role,HttpServletRequest request){
		
		try{
			password=toMd5(password);
			// 用户管理
			User user = new User();
			user.setName(name);
			user.setPassword(password);
			user.setRole(Integer.parseInt(role));
			userService.add(user);
			request.setAttribute("status", 1);
			
		}catch(Exception ex){
			request.setAttribute("status", 0);
			
		}
		return "/page/userAdd";
	}
	
	
	@RequestMapping("/edit/{id}")
	public String edit(@PathVariable(value = "id") Long id,HttpServletRequest request){
		if (null == id) {
			return "redirect:/page/userList.jsp";
		}
		
		User user=userService.getUser(id);
		
		if (null == user) {
			return "redirect:/page/userList.jsp";
		}
		
		request.setAttribute("user", user);
		
		return "/page/userEdit";
	}
	
	@RequestMapping("/update")
	public String update(User user,HttpServletRequest request){
		try{
		if (null == user) {
			
			System.out.println("user");
			request.setAttribute("status", 0);
			return "/page/userEdit";
		}

		
		if (null == user.getName() || user.getName().isEmpty()) {
			System.out.println("username");
			request.setAttribute("status", 0);
			return "/page/userEdit";
		}
		
		if (null == user.getPassword() || user.getPassword().isEmpty()) {
			System.out.println("userpassword");
			request.setAttribute("status", 0);
			return "/page/userEdit";
		}
		
		if (null == user.getRole() ) {
			System.out.println("user");
			request.setAttribute("status", 0);
			return "/page/userEdit";
		}
		user.setPassword(toMd5(user.getPassword()));
		userService.updateUser(user);
		request.setAttribute("status", 1);
		return "/page/userEdit";
		}
		catch(Exception e){
			request.setAttribute("status", 0);
			return "/page/userEdit";
		}
	
	}
	
	
	@RequestMapping("/editPassword")
	public String editPassword(String opassword, User user,HttpServletRequest request){
		try{
			User user1=userService.getUser(user.getId());
			opassword=toMd5(opassword);
			
			if (!opassword.equals(user1.getPassword())){
				request.setAttribute("pstatus", 0);
				return "/page/passwordEdit";
			}
			else{
				user.setPassword(toMd5(user.getPassword()));
				userService.updateUser(user);
				request.setAttribute("status", 1);
			}
		}
		catch(Exception ex){
			request.setAttribute("status", 0);
		}
		return "/page/passwordEdit";
		
	}
	
	
	public String toMd5(String s){
		byte[] bytes;
		bytes=s.getBytes();
		try{
			MessageDigest al=MessageDigest.getInstance("MD5");
			al.reset();
			al.update(bytes);
			return toHexString(al.digest(),"");
		}
		catch(NoSuchAlgorithmException e){
			
		}
		return null;

	}
	
	private String toHexString (byte[] bytes, String separator){
		StringBuilder hexString =new StringBuilder();
		for (byte b:bytes){
				String hex=Integer.toHexString(0xFF & b);
				if(hex.length()==1){
					hexString.append('0');
				}
				hexString.append(hex).append(separator);
		}
	return hexString.toString();
	}
	
}
